package com.tang.module.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.module.system.mapper.DictMapper;
import com.tang.module.system.entity.Dict;
import com.tang.module.system.service.DictService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典表(Dict)表服务实现类
 *
 * @author tang
 * @since 2022-01-20 11:49:22
 */
@Service("dictService")
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private DictMapper dictMapper;

    @Override
    public Map<String, List<Dict>> list(List<String> codeList) {
        Map<String, List<Dict>> map = new HashMap<>(codeList.size());
        for (String s : codeList) {
            List<Dict> dicts = dictMapper.selectList(Wrappers.<Dict>lambdaQuery()
                    .select(Dict::getDictKey, Dict::getDictValue)
                    .eq(Dict::getCode, s)
                    .ne(Dict::getDictKey, 0)
                    .orderByAsc(Dict::getSort));
            map.put(s,dicts);
        }
        return map;
    }

    @Override
    public List<Dict> tree() {
        //获取全部字典
        List<Dict> dictList = dictMapper.selectList(null);
        //第一次循环获取的是顶级字典
        return this.createTree(0L,dictList);
    }

    @Override
    public List<Dict> createTree(Long fid, List<Dict> dictList) {
        List<Dict> dicts = new ArrayList<>();
        //遍历寻找子节点
        for (Dict dict : dictList) {
            if (dict.getParentId().equals(fid)){
                dicts.add(dict);
                //设置子字典
                dict.setChildren(createTree(dict.getId(),dictList));
            }
        }
        return dicts;
    }
}
